<template>
	<a-modal
		:title="title"
		:width="modalWidth"
		:bodyStyle="bodyStyle"
		:visible="visible"
		:confirmLoading="confirmLoading"
		@ok="handleOk"
		@cancel="handleCancel"
		:destroyOnClose="true"
		:maskClosable="false"
	>
		<a-spin :spinning="confirmLoading">
			<a-form :form="form" autocomplete="off" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="题目分类">
					<a-select
						placeholder="题目分类"
						v-decorator="[
							'type',
							{
								rules: [{ required: true, message: '题目分类' }]
							}
						]"
					>
						<a-select-option :value="item.code" v-for="(item, index) in questionTypeList" :key="index">{{ item.name }}</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="题号">
					<a-input-number
						class="w100"
						placeholder="题号"
						v-decorator="[
							'sort',
							{
								rules: [{ required: true, message: '题号' }]
							}
						]"
					/>
				</a-form-item>
				<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="分值">
					<a-input-number
						class="w100"
						placeholder="分值"
						v-decorator="[
							'scores',
							{
								rules: [{ required: true, message: '分值' }]
							}
						]"
					/>
				</a-form-item>
				<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="题目"><a-textarea class="w100" placeholder="题目" v-decorator="['content']" /></a-form-item>
				<a-form-item label="题目图片">
					<div class="flex flex-align-center">
						<a-upload
							style="width: auto;"
							v-decorator="[
								'contentImgs',
								{
									valuePropName: 'file',
									getValueFromEvent: normFile
								}
							]"
							name="file"
							:action="uploadFile"
							:show-upload-list="false"
							list-type="picture-card"
							class="avatar-uploader"
							:headers="headers"
						>
							<img v-if="imageUrl" :src="imageUrl" alt="avatar" style="max-width: 200px;" />
							<div v-else>
								<a-icon :type="loading ? 'loading' : 'plus'" />
								<div class="ant-upload-text">上传题目图片</div>
							</div>
						</a-upload>
						<a v-if="imageUrl" href="javascript:;" class="del" @click="delImgs('contentImgs')"><a-icon type="delete" /></a>
					</div>
				</a-form-item>
				<a-form-item label="选项">
					<a-form-item v-for="(k, index) in selectlist" :key="k" :label="'选项' + selectValues[index]" :required="false">
						<a-input
							v-decorator="[
								`select[${k}]`,
								{
									validateTrigger: ['change', 'blur'],
									rules: [
										{
											required: true,
											whitespace: true,
											message: '请输入选项'
										}
									]
								}
							]"
							placeholder="请输入选项题目"
							style="width: 60%; margin-right: 8px"
						/>
						<a-icon v-if="selectlist.length > 1" class="dynamic-delete-button" type="minus-circle-o" :disabled="selectlist.length === 1" @click="() => delObj(k)" />
					</a-form-item>
					<a-form-item>
						<a-button type="dashed" style="width: 100%" @click="addObj">
							<a-icon type="plus" />
							添加选项
						</a-button>
					</a-form-item>
				</a-form-item>
				<a-form-item v-if="selectlist.length > 0" :labelCol="labelCol" :wrapperCol="wrapperCol" label="正确答案">
					<a-select
						placeholder="正确答案"
						v-decorator="[
							'answer',
							{
								rules: [
									{
										required: true,
										message: '请选择正确答案'
									}
								]
							}
						]"
					>
						<a-select-option :value="item" v-for="(item, index) in selectValues" :key="index">{{ item }}</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="题目解析"><a-textarea class="w100" placeholder="题目解析" v-decorator="['analysis']" /></a-form-item>
				<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="解析图片">
					<div class="flex flex-align-center">
						<a-upload
							style="width: auto;"
							v-decorator="[
								'analysisImgs',
								{
									valuePropName: 'file',
									getValueFromEvent: normAnalysisFile
								}
							]"
							name="file"
							:action="uploadFile"
							:show-upload-list="false"
							list-type="picture-card"
							class="avatar-uploader"
							:headers="headers"
						>
							<img v-if="analysisimgs" :src="analysisimgs" alt="avatar" style="max-width: 200px;" />
							<div v-else>
								<a-icon :type="analysisloading ? 'loading' : 'plus'" />
								<div class="ant-upload-text">上传解析图片</div>
							</div>
						</a-upload>
						<a v-if="analysisimgs" href="javascript:;" class="del" @click="delImgs('analysisImgs')"><a-icon type="delete" /></a>
					</div>
				</a-form-item>
			</a-form>
		</a-spin>
	</a-modal>
</template>

<script>
import { api } from '@/api/index.js';
import { ModalMixins } from '@/mixins';
function getBase64(img, callback) {
	const reader = new FileReader();
	reader.addEventListener('load', () => callback(reader.result));
	reader.readAsDataURL(img);
}
let maxId = -1;
export default {
	name: 'addAccountModal',
	mixins: [ModalMixins],
	data() {
		return {
			confirmDirty: false,
			selectlist: [],
			uploadFile: process.env.VUE_APP_API_BASE_URL + api.uploadFile,
			loading: false,
			imageUrl: '',
			analysisimgs: '',
			analysisloading: false,
			headers: {
				Authorization: window.localStorage.getItem('token')
			},
			selectValues: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
			questionTypeList: []
		};
	},
	created() {},
	methods: {
		add(record) {
			this.visible = true;
			this.imageUrl = '';
			this.analysisimgs = '';
			this.selectlist = [];
			this.loading = false;
			this.analysisloading = false;
			maxId = -1;
			if (record) {
				this.title = '编辑用户';
				this.isAdd = false;
				this.mdl = { ...record };
				this.init();
			} else {
				this.title = '新增题目';
				this.isAdd = true;
			}
			if (this.questionTypeList.length == 0) {
				this.getQuestionType();
			}
		},
		init() {
			let seletvalue = [];
			let selectlist = [];
			this.selectValues.forEach(item => {
				if (this.mdl['select' + item]) {
					selectlist.push(++maxId);
					seletvalue[maxId] = this.mdl['select' + item];
				}
			});
			this.selectlist = [...selectlist];
			if (this.mdl.contentImgs) {
				this.imageUrl = process.env.VUE_APP_API_BASE_URL + this.mdl.contentImgs;
			}
			if (this.mdl.analysisImgs) {
				this.analysisimgs = process.env.VUE_APP_API_BASE_URL + this.mdl.analysisImgs;
			}
			this.$nextTick(() => {
				this.form.setFieldsValue(this.$pick(this.mdl, 'analysis', 'analysisImgs', 'answer', 'content', 'contentImgs', 'scores', 'sort', 'type'));
				if (this.selectlist && this.selectlist.length > 0) {
					this.form.setFieldsValue({
						select: seletvalue
					});
				}
			});
		},
		close() {
			this.$emit('close');
			this.visible = false;
		},
		handleOk() {
			const _this = this;
			// 触发表单验证
			this.form.validateFields((err, values) => {
				// 验证表单没错误
				if (!err) {
					let { analysis, analysisImgs, answer, content, contentImgs, scores, sort, type } = values;
					let parameter = {
						analysis,
						analysisImgs,
						answer,
						content,
						contentImgs,
						scores,
						sort,
						type
					};
					if (values.select && values.select.length > 0) {
						let select = values.select.filter(item => !!item);
						for (var i = 0; i < select.length; i++) {
							parameter['select' + this.selectValues[i]] = select[i];
						}
						parameter.selectCount = select.length;
					}
					_this.confirmLoading = true;
					this.$postAction(!this.isAdd ? api.editQuestion : api.addQuestion, Object.assign({}, parameter, !this.isAdd ? { id: this.mdl.id } : null))
						.then(res => {
							if (res.code == 200) {
								_this.$message.success('保存成功');
								_this.$emit('ok');
								_this.form.resetFields();
								_this.visible = false;
							}
						})
						.finally(() => {
							_this.confirmLoading = false;
						});
				}
			});
		},
		handleCancel() {
			this.close();
		},
		addObj() {
			if (this.selectlist.length >= this.selectValues.length) {
				return false;
			}
			this.selectlist.push(++maxId);
		},
		delObj(k) {
			let list = this.selectlist.filter(key => key !== k);
			this.selectlist = list;
		},
		normFile(e) {
			if (Array.isArray(e)) {
				return e;
			}
			if (e.file.status === 'uploading') {
				this.loading = true;
				return;
			}
			if (e.file.status === 'done') {
				getBase64(e.file.originFileObj, imageUrl => {
					this.imageUrl = imageUrl;
					this.loading = false;
				});
			}
			return e && e.file && e.file.response && e.file.response.data ? e.file.response.data : null;
		},
		normAnalysisFile(e) {
			if (Array.isArray(e)) {
				return e;
			}
			if (e.file.status === 'uploading') {
				this.analysisloading = true;
				return;
			}
			if (e.file.status === 'done') {
				getBase64(e.file.originFileObj, imageUrl => {
					this.analysisimgs = imageUrl;
					this.analysisloading = false;
				});
			}
			return e && e.file && e.file.response && e.file.response.data ? e.file.response.data : null;
		},
		/* 获取题目类型 */
		getQuestionType() {
			this.$postAction(api.getConfig, {
				type: 'question'
			}).then(da => {
				this.questionTypeList = [...da.data];
			});
		},
		delImgs(type) {
			if (type == 'contentImgs') {
				this.imageUrl = '';
				this.form.setFieldsValue({
					contentImgs: ''
				});
			} else {
				this.analysisimgs = '';
				this.form.setFieldsValue({
					analysisImgs: ''
				});
			}
		}
	}
};
</script>

<style scoped>
.del {
	font-size: 30px;
	color: #f00;
}
</style>
